﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NewsMine.Storage;
using NewsMine.Utilities;
using NewsMine.DomainObjects;

namespace NewsDiscoveryEngine.Jobs
{
    public class CalculateFeedImageSizeJob:BaseJob
    {
        public FeedItem FeedItem { get; set; }

        public override bool ExecuteJob()
        {
            CalculateImageSizeForFeedImage(FeedItem);

            Defaults.IndexingQueue.Enqueue(FeedItem);

            return true;
        }


        public static void CalculateImageSizeForFeedImage(NewsMine.DomainObjects.FeedItem resultFeed)
        {
            try
            {
                if (!string.IsNullOrEmpty(resultFeed.ImageUrl))
                {
                    object storedSizeObject = Defaults.ImageSizeInfoStore.Get(resultFeed.ImageUrl);

                    Size imageSize = null;

                    if (storedSizeObject != null && storedSizeObject is Size)
                    {
                        imageSize = (Size)storedSizeObject;
                    }
                    else
                    {
                        imageSize = ImageSizeHelper.GetDimensionsFromUrl(resultFeed.ImageUrl);
                        Defaults.ImageSizeInfoStore.Replace(resultFeed.ImageUrl, imageSize);
                    }

                    if (imageSize.IsEmpty == false)
                    {
                        resultFeed.ImageWidth = imageSize.Width;
                        resultFeed.ImageHeight = imageSize.Height;
                    }
                }
            }
            catch (Exception ex)
            {
                TempLogger.Log("Error while calculating the image size.  for url =>" + resultFeed.ImageUrl, ex);
            }
        }

    }
}
